<?

class db_mongo
{
	/**
	 * @var Mongo
	 */
	private static $handle;

	private static $profiling_dbs = array();

	/**
	 *
	 * @return MongoDB
	 */
	public static function db( $db )
	{
		if ( !self::$handle )
		{
			self::$handle = config::get('mongo') ? new Mongo( config::get('mongo') ) : new Mongo();
			if ( config::get('debug') && !in_array($db, self::$profiling_dbs) )
			{
				self::$handle->$db->setProfilingLevel( MongoDB::PROFILING_ON );
				self::$profiling_dbs[] = $db;
			}
		}

		return self::$handle->$db;
	}

	/**
	 * @return MongoCollection
	 */
	public static function col( $db, $collection )
	{
		$mongo = self::db($db);
		return $mongo->$collection;
	}

	public static function get_profiling()
	{
		foreach ( self::$profiling_dbs as $db )
		{
			$profile = self::db($db)->{"system.profile"}->find()->sort(array('$natural' => -1));
			foreach ( $profile as $row )
			{
				$profiling[] = array(
					'info' => $row['info'],
					'time' => $row['millis']
				);
			}

			self::db($db)->setProfilingLevel( MongoDB::PROFILING_OFF );;
			self::db($db)->{"system.profile"}->drop();
		}

		return $profiling;
	}
}
